package com.apex.wx.service.impl;

import com.apex.common.util.JsonUtils;
import com.apex.oauth.security.domian.UserLoginDomain;
import com.apex.oauth.security.entity.SecurityUser;
import com.apex.security.api.entity.TBsdtWxUser;
import com.apex.security.api.entity.TUser;
import com.apex.oauth.security.domian.TBsdtUserRepository;
import com.apex.wx.service.WxLoginService;
import com.apex.oauth.security.util.ICECookieUtil;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.wiscom.is.IdentityFactory;
import com.wiscom.is.IdentityManager;
import com.wiscom.is.SSOToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by IntelliJ IDEA.
 * user:wangj
 * date:2018/4/8
 * Time: 20:36
 */
@Service
public class WxLoginServiceImpl implements WxLoginService {

    @Autowired
    private UserLoginDomain domain;

    @Autowired
    private TBsdtUserRepository restService;

    @Value("${sso.type:none}")
    private String type;

    @Value("${sso.ice.file.path:/EDU}")
    private String filePath;

    @Value("${sso.ice.domain:.suda.edu.cn}")
    private String iceDomain;

    @Override
    public boolean checkedLogin(HttpServletRequest request, HttpServletResponse response) {
        if ("ice".equals(type)) {
            try {
                String cookieValue = getDecodedCookieValue(request, "iPlanetDirectoryPro");
                if (!StringUtils.isEmpty(cookieValue)) {
                    IdentityFactory factory = IdentityFactory.createFactory(filePath);
                    IdentityManager im = factory.getIdentityManager();
                    String userid = im.getCurrentUser(cookieValue);
                    if(StringUtils.isEmpty(userid)){
                        return false;
                    }
                    TUser tUser= JsonUtils.toObject(domain.findByUserId(userid),TUser.class);
                    if(null!=tUser){
                        request.getSession().setAttribute("SESSION_USER_BEAN", tUser);
                        UserDetails userDetails = new SecurityUser(tUser);
                        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), "", userDetails.getAuthorities());
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        return true;
                    }
                    return false;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public boolean checkedWeixinLogin(HttpServletRequest request, HttpServletResponse response) {
        try {
            if (checkedLogin(request, response)) {
                return true;
            }
            String cookieValue = getDecodedCookieValue(request, "CookieWDirectoryPro");
            if (!StringUtils.isEmpty(cookieValue)) {
                String code=restService.login(cookieValue);
                if(!StringUtils.isEmpty(code)){
                    Any any= JsonIterator.deserialize(code);
                    if(null!=any){
                        String data=any.get("data").toString();
                        if(!StringUtils.isEmpty(data)){
                            TBsdtWxUser user=any.get("data").as(TBsdtWxUser.class);
                            if(null!=user&&!StringUtils.isEmpty(user.getPwd())&&!StringUtils.isEmpty(user.getUserid())){
                                IdentityFactory factory = IdentityFactory.createFactory(filePath);
                                IdentityManager im = factory.getIdentityManager();
                                boolean info=im.checkPassword(user.getUserid(),user.getPwd());
                                if(info){
                                    SSOToken token = im.createStoken(user.getUserid(),user.getPwd());
                                    ICECookieUtil.addCookie(response, iceDomain, token.getTokenValue());
                                    TUser tUser= JsonUtils.toObject(domain.findByUserId(user.getUserid()),TUser.class);
                                    request.getSession().setAttribute("SESSION_USER_BEAN", tUser);
                                    UserDetails userDetails = new SecurityUser(tUser);
                                    Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails.getUsername(), "", userDetails.getAuthorities());
                                    SecurityContextHolder.getContext().setAuthentication(authentication);
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
    public  String getDecodedCookieValue(HttpServletRequest request, String cookieName)  {
        Cookie all_cookies[] = request.getCookies();
        Cookie myCookie;
        String decodedCookieValue = null;
        if (all_cookies != null) {
            for (int i = 0; i < all_cookies.length; i++) {
                myCookie = all_cookies[i];
                if (myCookie.getName().equals(cookieName)) {
                    try {
                        decodedCookieValue = URLDecoder.decode(myCookie.getValue(), "GB2312");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return decodedCookieValue;
    }
}
